package com.rfsp.mcp.service;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import com.rfsp.common.pojo.po.OrgPO;
import com.rfsp.common.pojo.po.UserPO;
import com.rfsp.common.service.OrgService;
import com.rfsp.mcp.enums.McpConst;
import com.rfsp.mcp.mapper.AttachMapper;
import com.rfsp.mcp.mapper.AuthHisMapper;
import com.rfsp.mcp.pojo.po.*;
import com.rfsp.mcp.pojo.vo.PfmVO;
import com.rfsp.mcp.util.McpPdfUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rfsp.common.base.BaseService;
import com.rfsp.common.service.AreaService;
import com.rfsp.common.shiro.ShiroUtils;
import com.rfsp.common.util.StringUtil;
import com.rfsp.common.util.XssUtils;
import com.rfsp.mcp.mapper.AuthMapper;
import com.rfsp.mcp.mapper.FinanceHisMapper;
import com.rfsp.mcp.mapper.FinanceMapper;
import com.rfsp.mcp.pojo.dto.AuthDTO;
import com.rfsp.mcp.pojo.dto.AuthStopDTO;
import com.rfsp.mcp.pojo.sdto.AuthSDTO;
import com.rfsp.common.pojo.sdto.PageSDTO;
import com.rfsp.mcp.pojo.vo.AuthVO;

@Service
public class AuthService extends BaseService<AuthPO> {
	
	public Logger logger = LoggerFactory.getLogger(AuthService.class);

    @Autowired
    AuthMapper authMapper;

	@Autowired
	AuthHisMapper authHisMapper;

    @Autowired
    FinanceMapper financeMapper;

    @Autowired
    FinanceHisMapper financeHisMapper;

	@Autowired
	AreaService areaCodeService;

	@Autowired
	SystemCodeService systemCodeService;

	@Autowired
    OrgService orgService;

	@Autowired
	CfcaService cfcaService;

	@Autowired
    AttachMapper attachMapper;

	/**上传地址*/
    @Value("${mcp.file-pdf-path-auth}")
    private String filePDFPath;

	public PageInfo<AuthVO> get(AuthSDTO sdto, PageSDTO pageSdto){
        if(pageSdto!=null){
            PageHelper.startPage(pageSdto.getPageNum(), pageSdto.getPageSize());
        }
        List<AuthVO> voList=authMapper.get(sdto);
        PageInfo<AuthVO> page = new PageInfo(voList);
        return page;
    }
	public List<AuthVO> get(AuthSDTO sdto){
		List<AuthVO> voList=authMapper.get(sdto);
		return voList;
	}
	public AuthVO getById(Long id){
		AuthPO e=mapper.selectByPrimaryKey(id);
		AuthVO vo=new AuthVO();
		BeanUtils.copyProperties(e,vo);
		return vo;
	}

	public AuthVO getAuthDetailById(Long id){
		return authMapper.getAuthDetailById(id);
	}


	public Integer updateById(Long id,AuthDTO dto){

		dto.setId(id);
		AuthPO po=new AuthPO();
		BeanUtils.copyProperties(dto,po);

		Integer count=this.update(po);

		//保存历史表
		AuthVO vo=this.getById(id);
		AuthHisPO hisPO = new AuthHisPO();
		BeanUtils.copyProperties(vo, hisPO);
		hisPO.setId(null);
		hisPO.setFkid(vo.getId());

		authHisMapper.insertSelective(hisPO);

		return count;
	}

	/**
     * 撤回授权
     * @param dto
     * @return 返回错误信息
     */
	public String revokeApply(AuthStopDTO dto) {

    	AuthPO auth = this.get(dto.getId());
    	FinancePO finance = financeMapper.getByAuthId(dto.getId());


    	Date now = new Date();
    	UserPO userPO = ShiroUtils.getCurrentUser();


    	if("1".equals(finance.getFinanceStatus()) && "1".equals(finance.getFinanceViewStatus()) ) {
    		finance.setFinanceStatus("3");
    		finance.setRevokeApplyReason(dto.getRevokeApplyReason());
    		finance.setRevokeApplyTime(now);
    		finance.setRevokeApplyUserName(userPO.getUserName());
    		finance.setRevokeApplyUserId(userPO.getId());
            finance.setOptTime(now);
            finance.setOptType("3");
            finance.setOptUserId(userPO.getId());

    		auth.setAuthStatus("3");
    		auth.setRevokeApplyReason(dto.getRevokeApplyReason());
    		auth.setRevokeApplyTime(now);
    		auth.setRevokeApplyUserName(userPO.getUserName());
    		auth.setRevokeApplyUserId(userPO.getId());
    		auth.setRevokeType("3");
    		auth.setOptTime(now);
            auth.setOptType("3");
            auth.setOptUserId(userPO.getId());

    	}else if("1".equals(finance.getFinanceStatus()) && "2".equals(finance.getFinanceViewStatus()) ) {
    		finance.setRevokeApplyReason(dto.getRevokeApplyReason());
    		finance.setRevokeApplyTime(now);
    		finance.setRevokeApplyUserName(userPO.getUserName());
    		finance.setRevokeApplyUserId(userPO.getId());
    		finance.setRevokeVerifyStatus("1");//撤销审核状态
            finance.setOptTime(now);
            finance.setOptType("2");
            finance.setOptUserId(userPO.getId());

    		auth.setRevokeApplyReason(dto.getRevokeApplyReason());
    		auth.setRevokeApplyTime(now);
    		auth.setRevokeApplyUserName(userPO.getUserName());
    		auth.setRevokeApplyUserId(userPO.getId());
    		auth.setRevokeVerifyStatus("1");//撤销审核状态
    		auth.setRevokeType("2");
    		auth.setOptTime(now);
            auth.setOptType("2");
            auth.setOptUserId(userPO.getId());
    	}else if("2".equals(finance.getFinanceStatus())) {
    		finance.setRevokeApplyReason(dto.getRevokeApplyReason());
    		finance.setRevokeApplyTime(now);
    		finance.setRevokeApplyUserName(userPO.getUserName());
    		finance.setRevokeApplyUserId(userPO.getId());
    		finance.setRevokeVerifyStatus("1");//撤销审核状态
            finance.setOptTime(now);
            finance.setOptType("2");
            finance.setOptUserId(userPO.getId());

    		auth.setRevokeApplyReason(dto.getRevokeApplyReason());
    		auth.setRevokeApplyTime(now);
    		auth.setRevokeApplyUserName(userPO.getUserName());
    		auth.setRevokeApplyUserId(userPO.getId());
    		auth.setRevokeVerifyStatus("1");//撤销审核状态
    		auth.setRevokeType("2");
    		auth.setOptTime(now);
            auth.setOptType("2");
            auth.setOptUserId(userPO.getId());
    	}


    	int fint = financeMapper.updateByPrimaryKeySelective(finance);
    	int aint = this.update(auth);

    	AuthHisPO authHisPO = new AuthHisPO();
    	BeanUtils.copyProperties(auth, authHisPO);
    	authHisPO.setId(null);
    	authHisPO.setFkid(auth.getId());
    	int ahint = authHisMapper.insertSelective(authHisPO);


    	FinanceHisPO financeHisPO = new FinanceHisPO();
    	BeanUtils.copyProperties(finance, financeHisPO);
    	financeHisPO.setId(null);
    	financeHisPO.setFkid(finance.getId());
    	int fhint = financeHisMapper.insertSelective(financeHisPO);


    	log.info("fint="+fint);
    	log.info("aint="+aint);
    	log.info("fhint="+fhint);
    	log.info("ahint="+ahint);

    	return finance.getFinanceViewStatus();
    }


	public void combo(AuthVO vo){
		vo.setAuthStatusStr(McpConst.AuthStatus123.getVal(vo.getAuthStatus()));
        vo.setAreaName(areaCodeService.getFullAddress(vo.getAreaCode()));
    }
    public void combo(List<AuthVO> voList){
		voList.forEach(this::combo);
    }



    public AuthDTO savePdf(AuthDTO dto) throws Exception {

    	Date now = new Date();
    	UserPO nowUser = ShiroUtils.getCurrentUser();
    	OrgPO nowOrg = ShiroUtils.getCurrentOrg();
		PfmVO pfm = ShiroUtils.getAttribute("mcp_pfm");
		OrgYbjPO orgYbjPO =  ShiroUtils.getAttribute("org_ybj");

    	OrgPO bankOrg = orgService.get(dto.getBankOrgId());

    	logger.info("bankOrg="+bankOrg);

    	String dirPath = filePDFPath.replaceFirst("date", StringUtil.dateToString(now, "yyyy/MM/dd"));


    	AuthPO authPO = new AuthPO();
    	authPO.setAid(this.getAID());
    	authPO.setBankOrgId(dto.getBankOrgId());
    	authPO.setAuthStartTime(StringUtil.stringToDate(dto.getAuthStartTime(), "yyyy-MM-dd"));
    	authPO.setAuthEndTime(StringUtil.stringToDate(dto.getAuthEndTime(), "yyyy-MM-dd"));
    	authPO.setAuthCreateTime(now);
    	authPO.setAuthCreateUserId(nowUser.getId());
		if("0".equals(pfm.getItfType()))
			authPO.setAuthNo(systemCodeService.getBussCode("auth"));
		else
			authPO.setAuthNo(systemCodeService.getBussCode("auth-pfm"));
    	authPO.setAuthStatus("0");
    	authPO.setMiOrgId(nowOrg.getId());
    	authPO.setOptTime(now);
    	authPO.setOptType("1");
    	authPO.setOptUserId(nowUser.getId());
    	authPO.setFilePath(dirPath+authPO.getAuthNo()+".pdf");
    	authPO.setRemark1(dto.getSignType());// 1=签名，0=不签名
    	authPO.setPfmId(pfm.getId());
    	authPO.setOrgYbjId(orgYbjPO.getId());

    	logger.info("auth="+authPO);
    	int i = authMapper.insertSelective(authPO);

    	AuthHisPO authHisPO = new AuthHisPO();
    	BeanUtils.copyProperties(authPO, authHisPO);
    	authHisPO.setId(null);
    	authHisPO.setFkid(authPO.getId());
    	authHisMapper.insertSelective(authHisPO);

    	//======================================================
        // 张超让存在这，方便文件系统访问时使用
        File authPDF = new File(authPO.getFilePath());
        if(authPDF.exists()) {
        	AttachPO attach = new AttachPO();
            attach.setAttachType("a");
            attach.setDocumentId(authPO.getId());
            attach.setDocumentNo(authPO.getAuthNo());
            attach.setOptTime(authPO.getOptTime());
            attach.setOptType(authPO.getOptType());
            attach.setOptUserId(authPO.getOptUserId());
            attach.setUploadTime(authPO.getOptTime());
            attach.setFileName(authPO.getFilePath());
            attach.setFileSize(authPDF.length()/1048576l);
            attach.setInifileName(authPDF.getName());
            attachMapper.insertSelective(attach);
        }
        //======================================================


    	String[] hashAndId = null;

    	if(i > 0) {
    		BeanUtils.copyProperties(authPO, dto);
    		dto.setMiOrgName(XssUtils.replaceUnXssAll(nowOrg.getOrgName()));
    		dto.setBankName(XssUtils.replaceUnXssAll(bankOrg.getOrgName()));
    		dto.setBankOrgCode(bankOrg.getOrgCode());
    		dto.setAuthStartTimeStr(dto.getAuthStartTime().split("-")[0]+"年"+dto.getAuthStartTime().split("-")[1]+"月"+dto.getAuthStartTime().split("-")[2]+"日");
        	dto.setAuthEndTimeStr(dto.getAuthEndTime().split("-")[0]+"年"+dto.getAuthEndTime().split("-")[1]+"月"+dto.getAuthEndTime().split("-")[2]+"日");
        	McpPdfUtil.buildAuthPDF(dto, dirPath);

        	if("1".equals(dto.getSignType())) {
        		hashAndId = cfcaService.autoCalculatePdfHash(dto.getFilePath(), XssUtils.replaceUnXssAll(dto.getSealImage()), dto.getAuthNo());

        		dto.setCfcaHash(hashAndId[0]);
        		dto.setCfcaId(hashAndId[1]);
        	}
    	}
    	
    	return dto;
    }



	public AuthDTO saveYBDPdf(AuthDTO dto) throws Exception {

		Date now = new Date();
		UserPO nowUser = ShiroUtils.getCurrentUser();
		OrgPO nowOrg = ShiroUtils.getCurrentOrg();
		PfmVO pfm = ShiroUtils.getAttribute("mcp_pfm");
		OrgYbjPO orgYbjPO =  ShiroUtils.getAttribute("org_ybj");

		OrgPO bankOrg = orgService.get(dto.getBankOrgId());

		logger.info("bankOrg="+bankOrg);

		String dirPath = filePDFPath.replaceFirst("date", StringUtil.dateToString(now, "yyyy/MM/dd"));


		AuthPO authPO = new AuthPO();
		authPO.setAid(this.getAID());
		authPO.setBankOrgId(dto.getBankOrgId());
		authPO.setAuthStartTime(StringUtil.stringToDate(dto.getAuthStartTime(), "yyyy-MM-dd"));
		authPO.setAuthEndTime(StringUtil.stringToDate(dto.getAuthEndTime(), "yyyy-MM-dd"));
		authPO.setAuthCreateTime(now);
		authPO.setAuthCreateUserId(nowUser.getId());
		if("0".equals(pfm.getItfType()))
			authPO.setAuthNo(systemCodeService.getBussCode("auth"));
		else
			authPO.setAuthNo(systemCodeService.getBussCode("auth-pfm"));
		authPO.setAuthStatus("0");
		authPO.setMiOrgId(nowOrg.getId());
		authPO.setOptTime(now);
		authPO.setOptType("1");
		authPO.setOptUserId(nowUser.getId());
		authPO.setFilePath(dirPath+authPO.getAuthNo()+".pdf");
		authPO.setRemark1(dto.getSignType());// 1=签名，0=不签名
    	authPO.setPfmId(pfm.getId());
    	authPO.setOrgYbjId(orgYbjPO.getId());

		logger.info("auth="+authPO);
		int i = authMapper.insertSelective(authPO);

		AuthHisPO authHisPO = new AuthHisPO();
		BeanUtils.copyProperties(authPO, authHisPO);
		authHisPO.setId(null);
		authHisPO.setFkid(authPO.getId());
		authHisMapper.insertSelective(authHisPO);

		//======================================================
		// 张超让存在这，方便文件系统访问时使用
		File authPDF = new File(authPO.getFilePath());
		if(authPDF.exists()) {
			AttachPO attach = new AttachPO();
			attach.setAttachType("a");
			attach.setDocumentId(authPO.getId());
			attach.setDocumentNo(authPO.getAuthNo());
			attach.setOptTime(authPO.getOptTime());
			attach.setOptType(authPO.getOptType());
			attach.setOptUserId(authPO.getOptUserId());
			attach.setUploadTime(authPO.getOptTime());
			attach.setFileName(authPO.getFilePath());
			attach.setFileSize(authPDF.length()/1048576l);
			attach.setInifileName(authPDF.getName());
			attachMapper.insertSelective(attach);
		}
		//======================================================


		String[] hashAndId = null;

		if(i > 0) {
			BeanUtils.copyProperties(authPO, dto);
			dto.setMiOrgName(XssUtils.replaceUnXssAll(nowOrg.getOrgName()));
			dto.setBankName(XssUtils.replaceUnXssAll(bankOrg.getOrgName()));
			dto.setBankOrgCode(bankOrg.getOrgCode());
			dto.setAuthStartTimeStr(dto.getAuthStartTime().split("-")[0]+"年"+dto.getAuthStartTime().split("-")[1]+"月"+dto.getAuthStartTime().split("-")[2]+"日");
			dto.setAuthEndTimeStr(dto.getAuthEndTime().split("-")[0]+"年"+dto.getAuthEndTime().split("-")[1]+"月"+dto.getAuthEndTime().split("-")[2]+"日");
			McpPdfUtil.buildAuthPDFByYBD(dto, dirPath);

			if("1".equals(dto.getSignType())) {
				hashAndId = cfcaService.autoCalculatePdfHash(dto.getFilePath(), XssUtils.replaceUnXssAll(dto.getSealImage()), dto.getAuthNo());

				dto.setCfcaHash(hashAndId[0]);
				dto.setCfcaId(hashAndId[1]);
			}
		}

		return dto;
	}
    
    
    
    public boolean signPDF(AuthDTO dto) throws Exception {
    	
    	String inputPath = XssUtils.replaceUnXssAll(dto.getFilePath());
    	return cfcaService.synthesizeOuterSignature(XssUtils.replaceUnXssAll(dto.getCfcaSignature()), XssUtils.replaceUnXssAll(dto.getCfcaId()), inputPath);
    	
    }
    
}
